<?php namespace dmq;

/**
 * Super class that all the Controller inherits from.
 * @abstract
 */
abstract class Controller
{
	private $output;	// (string), Markup output buffered through the view.
	private $css;		// (array), CSS files to be loaded.
	private $js;		// (array), JavaScript files to be loaded.
	private $ijs;		// (string), Internal javascript to be executed.
	private $title;		// (string), Page title.
	private $name;		// (string), Section name.

	protected $view;			// (View).
	protected $model;			// (Model).
	protected $useDb = false; 	// Should the model have access to the database? False is default.

	/**
	* This method must be implemented by child classes.
	* Will be called by the constructor.
    * @abstract
    */
	abstract protected function doControll();
	
	/**
    * The constructor and should never be overridden.
    * @final
    */
	final public function __construct() {
		$this->output = '';
		$this->css = array();
		$this->js = array();
		$this->ijs = '';
		$this->title = '';
		$this->name = ucfirst( strtolower( preg_replace( '/Controller$/i', '', get_class( $this ) ) ) );

		$viewName = $this->name . 'View';
		require_once Settings::MVC_PATH . $viewName . '.php';
		$this->view = new $viewName();
		
		$modelName = $this->name . 'Model';
		require_once Settings::MVC_PATH . $modelName . '.php';
		$this->model = new $modelName( $this->useDb );

		$this->doControll();

		$this->output( $this->view->markup() );
	}

	/**
	* function output
    * @final
    * handles all the output after createing the page.
    */
	final public function output( $output = false )
	{
		if ( $output === false )
		{
			return $this->output;
		}
		else
		{
			$this->output .= $output;
		}
	}

	/**
	* function ijs
    * @final
    * handles internal javascript in the code.
    */
	final public function ijs( $ijs = false )
	{
		if ( $ijs === false )
		{
			return $this->ijs;
		}
		else
		{
			$this->ijs .= $ijs;
		}
	}
	
	/**
	* function css
    * @final
    * handles css in the code.
    */
	final public function css( $css = false )
	{
		if ( $css === false )
		{
			return $this->css;
		}
		else
		{
			$this->css[] = $css;
		}
	}
	
	/**
	* function js
    * @final
    * handles javascript of the application.
    */
	final public function js( $js = false )
	{
		if ( $js === false )
		{
			return $this->js;
		}
		else
		{
			$this->js[] = $js;
		}
	}
	
	/**
	* function title
    * @final
    * handles the title of the page.
    */
	final public function title( $title = false )
	{
		if ( $title === false )
		{
			return $this->title;
		}
		else
		{
			$this->title = $title;
		}
	}

	/**
	* function name
    * @final
    * handles the name of each view.
    */
	final public function name()
	{
		return $this->name;
	}
}
